<template>
  <div class="selfCheckScrapRecord zy-content">
    <!-- 搜索区域 - 调整为与materialMoldCode页面一致的样式 -->
    <div class="search clear">
      <div class="search-box-layout">
        <Row :gutter="24">
          <Col span="6">
          <p class="label">物料编码</p>
          <div class="ipt">
            <Input v-model="searchParams.materialCode" placeholder="请输入物料编码" clearable />
          </div>
          </Col>
          <Col span="6">
          <p class="label">物料名称</p>
          <div class="ipt">
            <Input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable />
          </div>
          </Col>
          <Col span="6">
          <p class="label">项目名称</p>
          <div class="ipt">
            <Input v-model="searchParams.projectName" placeholder="请输入项目名称" clearable />
          </div>
          </Col>
          <Col span="6">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button type="primary" class="search-btn" @click="handleSearch">搜索</Button>
              <Button class="reset-btn" @click="resetSearch">重置</Button>
            </div>
          </div>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
        <Button @click="showAddModal" style="color: #fff!important;">新增</Button>
      </div>

      <!-- 表格区域 -->
      <div class="tableContent">
        <Table class="resizable-table" border :columns="columns" ellipsis ref="selection" stripe :data="tableData"
          @on-selection-change="onSelectChange">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="editRow(row)"><i class="iconfont zy-common-bianji"></i>编辑</span>
            <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"></i>{{
              $t('common.Delete')
            }}</span>
          </template>
        </Table>
      </div>

      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectedIds.length" />
        <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
          @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
      </div>
    </div>

    <Modal v-model="modalVisible" :title="modalTitle" width="800" @on-cancel="resetForm">
      <Form ref="form" :model="formData" :label-width="120">
        <Row :gutter="16">
          <Col span="24">
          <FormItem label="客户名称" prop="customerName">
            <Input v-model="formData.customerName" placeholder="请输入客户名称" />
            <div v-if="errors.customerName" class="error-tip">{{ errors.customerName }}</div>
          </FormItem>
          </Col>

          <Col span="24">
          <FormItem label="项目名称" prop="projectName">
            <Input v-model="formData.projectName" placeholder="请输入项目名称" />
            <div v-if="errors.projectName" class="error-tip">{{ errors.projectName }}</div>
          </FormItem>
          </Col>

          <Col span="24">
          <FormItem label="用户" prop="userId">
            <Select v-model="formData.userId" filterable clearable remote :remote-method="getUserList"
              :loading="userLoading" placeholder="请输入工号或姓名搜索" style="width: 100%;">
              <Option v-for="user in userList" :key="user.id" :value="user.id" :label="user.username">{{ user.showName }}</Option>
            </Select>
          </FormItem>
          </Col>

          <Col span="24">
          <FormItem label="已选择物料" prop="selectedMaterials">
            <Button type="primary" @click="addMaterialRow" style="margin-bottom: 10px;">
              <i class="iconfont zy-common-tianjia"></i> 添加物料
            </Button>

            <!-- 已选择物料列表 - 直接显示select组件 -->
            <div class="selected-materials-list"
              v-if="formData.selectedMaterials && formData.selectedMaterials.length > 0">
              <div class="material-item" v-for="(item, index) in formData.selectedMaterials" :key="index">
                <div style="display: flex;justify-content: space-between;align-items: center;padding: 5px 0">
                  <Select v-model="item.materialId" filterable clearable remote :remote-method="handleMaterialRemote"
                    :loading="materialLoading" placeholder="请输入物料编码搜索" style="width: calc(100% - 80px);">
                    <Option v-for="mat in materialList" :key="mat.id" :value="mat.id" :label="mat.materialCode">{{ mat.materialCode }} - {{ mat.materialName }}</Option>
                  </Select>
                  <Button type="text" @click="removeMaterial(index)" class="delete-btn" style="margin-left: 5px">
                    <i class="iconfont zy-common-shanchu"></i> 删除
                  </Button>
                </div>
              </div>
            </div>
            <div v-else class="no-materials">暂无已选择物料</div>
            <div v-if="errors.selectedMaterials" class="error-tip">{{ errors.selectedMaterials }}</div>
          </FormItem>
          </Col>
        </Row>
      </Form>

      <div slot="footer">
        <Button @click="modalVisible = false">{{ $t("common.Cancel") }}</Button>
        <Button type="primary" @click="submitForm" :loading="submitLoading">
          确认
        </Button>
      </div>
    </Modal>

    <!-- 删除确认弹框 -->
    <Modal :mask-closable="false" v-model="deleteShow" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.sureDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="deleteSure">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>


  </div>
</template>

<script>
import fileDownload from "js-file-download";

export default {
  name: "marketingBalance",
  data() {
    return {
      materialList: [],
      materialLoading: false,
      deleteShow: false,
      currentDeleteId: null,
      // 搜索相关
      searchParams: {
        materialCode: '',
        materialName: '',
        projectName: ''
      },

      // 表格相关
      columns: [
        { type: "selection", width: 60, align: "center" },
        { title: "客户名称", key: "customerName", minWidth: 150, align: "center" },
        { title: "用户名称", key: "realname", minWidth: 120, align: "center" },
        { title: "项目名称", key: "projectName", minWidth: 150, align: "center" },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 200,
          align: "center"
        }
      ],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30, 50],
      selectedIds: [],

      // 表单相关
      modalVisible: false,
      modalTitle: "新增项目物料配置",
      submitLoading: false,
      isEdit: false,
      currentId: null,
      errors: {},
      // 用户相关
      userList: [],
      userLoading: false,
      formData: {
        id: null,
        customerName: "",
        projectName: "",
        userId: null,
        selectedMaterials: [] // 存储已选择的物料数组
      },
    };
  },

  mounted() {
    this.getList();
    // 移除页面加载时的物料查询，改为通过remote-method按需加载
    this.getUserList('');
  },

  methods: {
    getUserList(query) {
      console.log(query)
      this.userLoading = true;
      return this.axios({
        method: 'get',
        url: '/basic/user/searchOAUser',
        params: {
          key: query,
          pageNum: 1,
          pageSize: 50 // 设置较大的pageSize以获取更多数据
        }
      }).then(res => {
        if (res.code === 200) {
          this.userList = res.data.map(item => ({
            ...item,
            showName: item.empno + '----' + item.username
          }));
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true });
          this.userList = [];
        }
      }).finally(() => {
        this.userLoading = false;
      });
    },
    // 获取当前用户ID
    getCurrentUserId() {
      try {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
          const user = JSON.parse(userInfo);
          return user.id || null;
        }
        const sessionUserInfo = sessionStorage.getItem('userInfo');
        if (sessionUserInfo) {
          const user = JSON.parse(sessionUserInfo);
          return user.id || null;
        }
        return null;
      } catch (error) {
        console.error('获取用户ID失败:', error);
        return null;
      }
    },

    // 搜索物料 - 使用materialCode进行远程检索
    handleMaterialRemote(query) {
      // 确保只使用materialCode进行查询，可能需要从查询字符串中提取materialCode部分
      // 如果查询字符串包含"-"，则只取前面的部分作为materialCode
      let materialCodeQuery = query;
      if (query && typeof query === 'string' && query.includes('-')) {
        // 提取"-"前面的部分作为materialCode
        materialCodeQuery = query.split('-')[0].trim();
      }
      
      this.materialLoading = true;
      return this.axios({
        method: 'POST',
        url: '/dms/material/page',
        data: {
          materialCode: materialCodeQuery, // 只使用materialCode作为查询参数
          pageNum: 1,
          pageSize: 100 // 查询100条数据
        }
      }).then(res => {
        if (res.code === 200) {
          // 合并结果，避免覆盖已有的物料数据
          const newMaterials = res.data.records || [];
          newMaterials.forEach(newMat => {
            const exists = this.materialList.some(existingMat => existingMat.id === newMat.id);
            if (!exists) {
              this.materialList.push(newMat);
            }
          });
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true });
        }
      }).finally(() => {
        this.materialLoading = false;
      });
    },

    // 获取列表数据
    getList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };

      this.axios({
        method: "POST",
        url: "/dms/supply/marketing/balance/config/page",
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true });
        }
      }).catch(error => {
        console.error('获取列表数据失败:', error);
        this.$Message.error('获取列表数据失败');
      });
    },

    // 搜索
    handleSearch() {
      this.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetSearch() {
      this.searchParams = {
        materialCode: '',
        materialName: '',
        projectName: ''
      };
      this.handleSearch();
    },

    // 显示新增模态框
    async showAddModal() {
      this.modalTitle = "新增项目物料配置";
      this.isEdit = false;
      this.currentId = null;
      this.resetForm();
      // 确保有用户数据，但不再重复查询物料数据
      if (this.userList.length === 0) {
        await this.getUserList('');
      }
      this.modalVisible = true;
    },

    // 编辑行
    async editRow(row) {
      this.modalTitle = "编辑项目物料配置";
      this.isEdit = true;
      this.currentId = row.id;
      
      // 加载用户数据
      await this.getUserList(row.realname);
      
      // 循环查询已选择的物料，使用行内的materialCode
      if (row.materialList && row.materialList.length > 0) {
        // 存储已查询到的物料编码，避免重复查询
        const queriedMaterialCodes = new Set();

        // 批量查询物料信息
        for (const materialItem of row.materialList) {
          // 确保有materialCode
          if (materialItem.materialCode && !queriedMaterialCodes.has(materialItem.materialCode)) {
            await this.queryMaterialByCode(materialItem.materialCode);
            queriedMaterialCodes.add(materialItem.materialCode);
          }
        }
      }
      
      // 设置表单数据
      this.formData = row;
      this.formData.selectedMaterials = row.materialList || [];
      this.modalVisible = true;
    },
    
    // 根据物料编码查询物料信息
    async queryMaterialByCode(materialCode) {
      try {
        const res = await this.axios({
          method: 'POST',
          url: '/dms/material/page',
          data: {
            materialCode: materialCode, // 使用物料编码作为查询参数
            pageNum: 1,
            pageSize: 100
          }
        });
        
        if (res.code === 200 && res.data.records) {
          // 将查询到的物料添加到materialList中，避免重复
          res.data.records.forEach(mat => {
            // 检查是否已存在相同ID的物料
            const exists = this.materialList.some(item => item.id === mat.id);
            if (!exists) {
              this.materialList.push(mat);
            }
          });
        }
      } catch (error) {
        console.error('查询物料信息失败:', error);
      }
    },

    // 添加物料行
    addMaterialRow() {
      // 直接添加一行空的物料选择
      const list = {...this.formData}
      list.selectedMaterials.push({
        materialId: null
      });
      this.formData = list

      // 页面加载时已经查询过物料列表，这里不需要再次查询
    },

    // 修改handleMaterialRemote方法，确保返回的数据正确处理 - 已在上面实现


    // 从已选择列表删除物料
    removeMaterial(index) {
      const list = {...this.formData}
      list.selectedMaterials.splice(index, 1);
      this.formData = list
    },

    // 验证表单
    validateForm() {
      this.errors = {};
      let isValid = true;

      // 验证客户名称
      if (!this.formData.customerName || this.formData.customerName.trim() === '') {
        this.errors.customerName = '请输入客户名称';
        isValid = false;
      }

      // 验证项目名称
      if (!this.formData.projectName || this.formData.projectName.trim() === '') {
        this.errors.projectName = '请输入项目名称';
        isValid = false;
      }

      // 验证用户
      if (!this.formData.userId) {
        this.errors.userId = '请选择用户';
        isValid = false;
      }

      // 验证是否选择了物料
      if (!Array.isArray(this.formData.selectedMaterials) || this.formData.selectedMaterials.length === 0) {
        this.errors.selectedMaterials = '请至少选择一个物料';
        isValid = false;
      } else {
        // 验证每个物料都已选择
        const emptySelections = this.formData.selectedMaterials.filter(item => !item.materialId);
        if (emptySelections.length > 0) {
          this.errors.selectedMaterials = '请选择所有物料';
          isValid = false;
        } else {
          // 验证是否有重复的物料
          const materialIds = this.formData.selectedMaterials.map(item => String(item.materialId));
          const uniqueIds = [...new Set(materialIds)];
          if (materialIds.length !== uniqueIds.length) {
            this.errors.selectedMaterials = '存在重复选择的物料';
            isValid = false;
          }
        }
      }

      return isValid;
    },

    // 提交表单
    submitForm() {
      // 验证表单
      if (!this.validateForm()) {
        return;
      }

      this.submitLoading = true;

      // 提交时构造materialList数组，只包含materialId字段
      const formData = {
        customerName: this.formData.customerName.trim(),
        projectName: this.formData.projectName.trim(),
        userId: this.formData.userId,
        materialList: this.formData.selectedMaterials.map(item => ({ materialId: item.materialId }))
      };

      // 编辑模式添加ID
      if (this.isEdit && this.currentId) {
        formData.id = this.currentId;
      }

      const url = this.isEdit
        ? "/dms/supply/marketing/balance/config/edit"
        : "/dms/supply/marketing/balance/config/add";

      this.axios.post(url, formData).then(res => {
        if (res.code === 200) {
          this.$Message.success(this.isEdit ? "修改成功" : "新增成功");
          this.modalVisible = false;
          this.getList();
        } else {
          this.$Message.error(res.msg || '操作失败');
        }
      }).catch(error => {
        this.$Message.error('操作失败: ' + (error.message || ''));
      }).finally(() => {
        this.submitLoading = false;
      });
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        customerName: "",
        projectName: "",
        userId: null,
        selectedMaterials: []
      };
      this.errors = {};
    },

    // 分页变化
    changePageNum(val) {
      this.pageNum = val;
      this.getList();
    },

    changePageSize(val) {
      this.pageSize = val;
      this.getList();
    },

    // 表格选择变化
    onSelectChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },

    // 删除确认
    deleteSure() {
      if (!this.currentDeleteId) return;

      this.axios.post('/dms/supply/marketing/balance/config/delete', {
        id: this.currentDeleteId
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success('删除成功');
          this.deleteShow = false;
          this.getList();
        } else {
          this.$Message.error(res.msg || '删除失败');
        }
      }).catch(error => {
        console.error('删除失败:', error);
        this.$Message.error('删除失败');
      }).finally(() => {
        this.currentDeleteId = null;
      });
    },

    // 删除行
    delRow(row) {
      this.currentDeleteId = row.id;
      this.deleteShow = true;
    }
  }
};
</script>

<style scoped lang="scss">
.selfCheckScrapRecord {
  .search-area {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }

  .ivu-form-item {
    margin-bottom: 16px;
  }

  .ivu-col {
    display: flex;
    flex-direction: column;
  }

  .ivu-form-item-content {
    flex: 1;
  }

  .label {
    text-align: left !important;
    /* 确保label靠左对齐 */
  }

  .operationBtn {
    margin: 0 8px;
    /* 增加按钮间距 */
    cursor: pointer;
    white-space: nowrap;
    /* 防止按钮换行 */

    &:hover {
      text-decoration: underline;
    }
  }

  .ivu-table-cell {
    padding: 12px 8px;
  }

  .error-tip {
    color: #ed4014;
    margin-top: 5px;
  }

  // 已选物料列表样式优化
  .selected-materials-list {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }

  // 物料项样式 - 删除按钮靠右，处理文本过长
  .material-item {
    display: flex;
    flex-wrap: nowrap;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  // 物料信息部分 - 处理过长文本
  .material-info {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 10px;
  }

  // 删除按钮样式
  .delete-btn {
    color: #ff4d4f;
    flex-shrink: 0; // 确保按钮不被压缩

    &:hover {
      color: #ff7875;
    }
  }

  .no-materials {
    padding: 20px;
    text-align: center;
    color: #909399;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
  }
}
</style>